package com.shanzhe.eshop.common.jdk;

import lombok.Data;

/**
 * @Author yinwei
 * @create 2021/9/29
 * @Version 1.0
 */
@Data
public class LikedListDemo<E> {

    private Node<E> first;

    private Node<E> last;

    private volatile int size;

    public Boolean add(E e){
        Node<E> l = last;
        Node<E> newNode = new Node<E>(l, e, null);
        last = newNode;
        if(l==null){
            first = newNode;
        }else{
            l.next = newNode;
        }
        size++;
        return true;
    }


    public E get(int index){
        return node(index).item;
    }


    public E removeFirst(){
        Node<E> f = first;
        if(f==null){
            throw new RuntimeException("链表为空");
        }
        final E item = f.item;
        Node<E> next = f.next;
        f.next = null;
        f.item = null;
        first = next;
        if(next!=null){
            next.prev = null;
        }else{
            last = null;
        }

        size--;
        return item;
    }

    public E removeLast(){
        Node<E> l = last;
        Node<E> prev =l.prev;
        E e = l.item;
        l.prev = null;
        l.item = null;
        last = prev;
        if(prev==null){
            first = null;
        }else{
            prev.next = null;
        }
        return e;
    }

    public E remove(int index){
        Node<E> node = node(index);
        E item = node.item;
        Node<E> prev= node.prev;
        Node<E> next = node.next;

        if(prev==null){
            first = next;
        }else{
            prev.next = next;
            node.prev = null;
        }

        if(next==null){
            last = prev;
        }else{
            next.prev = prev;
            node.next = null;
        }
        node.item = null;

        size--;
        return item;
    }


    public Node<E> node(int index){
        if(index>=0 && index<size){
            if(index < size>>1){
                Node<E> x = first;
                for(int i = 0;i<index;i++){
                    x = x;
                }
                return x;
            }else{
                Node<E> x  = last;
                for(int i = size-1;i > index;i--){
                    x = x;
                }
                return  x;
            }
        }
        throw new RuntimeException("下标越界");
    }



    public static class Node<E>{
        private E item;
        private Node<E> prev;
        private Node<E> next;

        public Node(Node<E> prev, E element, Node next) {
            this.item = element;
            this.prev = prev;
            this.next = next;
        }
    }
}
